(function () {
    app.cp.register("UpdateClientOrderController", UpdateClientOrderController);
    function UpdateClientOrderController($scope, $rootScope, clientOrderService) {
        $scope.updateClientOrder = {
            orderAddressDTO: {},
            orderSummaryDTO: {},
            orderGoodsDTOs: []
        };
        $rootScope.$on("updateClientOrder", function (event, clientOrderId) {
            $.ajax({
                url: contextPath + "/clientOrder/get/" + clientOrderId,
                type: "GET",
                contentType: "application/json"
            }).done(function (result) {
                if (result.success === true) {
                    $scope.updateClientOrder = result.data;
                    $scope.orderGoodsDataSource.data(result.data.orderGoodsDTOs);
                    $.get("/projectCate/getByProjectId/" + $scope.updateClientOrder.projectId).done(function (result) {
                        $("#updateGoodsCategory").data("kendoComboBox").setDataSource(new kendo.data.DataSource({
                            data: result
                        }));
                    });
                    clientOrderService.findGoodsArchives($scope.updateClientOrder.projectId).done(function (data) {
                        $scope.goodsCode = data;
                    });
                    $scope.$apply();
                    $scope.updateWindow.center().open();
                }
            });
        });
        $scope.projectOptions = kendo.factory.getComboxOptions("/project/findAll", "projectId", {});
        $scope.goodsCategoryOptions = {
            dataSource: []
        };

        $scope.save = function () {
            if (!$scope.validator.validate())
                return;
            if (!$scope.updateClientOrder.vehicleTonnage) {
                $scope.updateClientOrder.vehicleTonnage = null;
            }
            if (!$scope.updateClientOrder.carType) {
                $scope.updateClientOrder.carType = null;
            }
            if ($scope.updateClientOrder.calculateType == "CAR_TYPE" && !$scope.updateClientOrder.carType) {
                kendo.factory.notifyError("车辆车型不能为空");
                return;
            }

            $scope.updateClientOrder.orderGoodsDTOs = $scope.goodsGrid.dataSource.data();
            $.ajax({
                url: contextPath + "/clientOrder/update",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify($scope.updateClientOrder)
            }).done(function (result) {
                if (result.success) {
                    $scope.updateWindow.close();
                    $rootScope.reloadGrid();
                    kendo.factory.notifySuccess("保存成功")
                } else {
                    kendo.factory.notifyError("保存失败" + result.message);
                }
            });
        };


        /*orderItems begin*/
        $scope.toolbar = [{name: "create"}];
        $scope.orderGoodsDataSource = new kendo.data.DataSource({
            data: [],
            schema: {
                model: {
                    fields: {
                        goodsCode: {type: "string"},
                        goodsName: {type: "string"},
                        goodsModel: {type: "string"},
                        itemQty: {
                            type: "number",
                            validation: {pattern: "^\\d+$", min: 1, required: {message: "数量为必填项"}},
                            defaultValue: 1
                        },
                        packageQty: {type: "string", defaultValue: 0},
                        weight: {
                            type: "number",
                            validation: {min: 0, required: {message: "重量为必填项"}},
                            defaultValue: 0
                        },
                        volume: {
                            type: "string",
                            validation: {pattern: "^\\d+(\\.\\d{0,6})?$", required: {message: "体积为必填项"}, min: 0},
                            defaultValue: "0"
                        },
                        worth: {
                            type: "string",
                            validation: {pattern: "^\\d+(\\.\\d{0,2})?$", min: 0},
                            defaultValue: "0"
                        },
                        remark: {type: "string"}
                    }
                }
            }
        });
        $scope.goodsCode = [];
        clientOrderService.findGoodsArchives().done(function (result) {
            $scope.goodsCode = result;
        });
        $scope.columns = [{
            field: "goodsCode",
            title: "货物编号",
            edit: function (e) {
                $scope.editItem = e.model;
            },
            editor: function (container, options) {
                var input = $("<input />");
                var index = container.closest("tr").index();
                input.appendTo(container);
                input.kendoAutoComplete({
                    dataTextField: "code",
                    dataSource: $scope.goodsCode,
                    select: function (e) {
                        console.info(e.dataItem);
                        var item = {
                            archivesId: e.dataItem.archivesId,
                            goodsName: e.dataItem.name,
                            goodsCode: e.dataItem.code,
                            goodsModel: e.dataItem.model,
                            weight1: e.dataItem.weight,
                            volume1: e.dataItem.volume,
                            salePrice: e.dataItem.salePrice,
                        };
                        $.extend($scope.orderGoodsDataSource.data().at(index), item);
                    },
                    change: function (e) {
                        if (!$scope.orderGoodsDataSource.data().at(index).archivesId) {
                            var item = {
                                goodsName: "",
                                goodsCode: this.value(),
                                goodsModel: "",
                                weight1: 1,
                                volume1: 1,
                                salePrice: 1
                            };
                            $.extend($scope.orderGoodsDataSource.data().at(index), item);
                        }
                    }
                }).data("kendoAutoComplete");
                $scope.$apply();
            },
        }, {
            field: "goodsName",
            title: "货物名称"
        }, {
            field: "goodsModel",
            title: "货物型号"
        }, {
            field: "itemQty",
            title: "数量",
            editor: function (container, options) {
                var input = $("<input type='number' required='required' class='k-textbox'/>");
                var index = container.closest("tr").index();
                input.appendTo(container);
                var dataItem = $scope.orderGoodsDataSource.data().at(index);
                input.on("change", function () {
                    var item = {
                        worth: this.value * dataItem.salePrice,
                        volume: this.value * dataItem.volume1,
                        weight: this.value * dataItem.weight1,
                        itemQty: this.value
                    };
                    $.extend($scope.orderGoodsDataSource.data().at(index), item);
                    var totalWorth = 0.0;
                    var totalQty = 0.0;
                    var totalVolume = 0.0;
                    var totalWeight = 0.0;
                    var obj = $scope.orderGoodsDataSource.data();
                    for (var i = 0; i < obj.length; i++) {
                        totalQty += parseFloat(obj[i].itemQty);
                        totalWorth += parseFloat(obj[i].worth);
                        totalVolume += parseFloat(obj[i].volume);
                        totalWeight += parseFloat(obj[i].weight);
                    }
                    $scope.updateClientOrder.orderSummaryDTO.totalVolume = totalVolume;
                    $scope.updateClientOrder.orderSummaryDTO.totalItemQty = totalQty;
                    $scope.updateClientOrder.orderSummaryDTO.totalGoodsWorth = totalWorth;
                    $scope.updateClientOrder.orderSummaryDTO.totalWeight = totalWeight;
                    $scope.$apply();
                });
            }
        }, {
            field: "packageQty",
            title: "件数"
        }, {
            field: "volume",
            title: "体积(m³)"
        }, {
            field: "weight",
            title: "重量(kg)"
        }, {
            field: "worth",
            title: "货值"
        }, {
            field: "remark",
            title: "备注"
        }, {
            command: "destroy"
        }];
        /*orderItems end*/

        $scope.$watchCollection('orderGoodsDataSource', function (newObj, oldObj) {
            var obj = newObj.data();
            if (obj.length < 1)return;
            var totalQty = 0;
            var totalPQty = 0;
            var totalVolume = 0.0;
            var totalWeight = 0.0;
            var totalWorth = 0.0;
            for (var i = 0; i < obj.length; i++) {
                totalQty += parseInt(obj[i].itemQty);
                totalPQty += parseInt(obj[i].packageQty);
                totalVolume += parseFloat(obj[i].volume);
                totalWeight += parseFloat(obj[i].weight);
                totalWorth += parseFloat(obj[i].worth);
            }
            $scope.updateClientOrder.orderSummaryDTO.totalItemQty = totalQty;
            $scope.updateClientOrder.orderSummaryDTO.totalPackageQty = totalPQty;
            $scope.updateClientOrder.orderSummaryDTO.totalVolume = totalVolume;
            $scope.updateClientOrder.orderSummaryDTO.totalWeight = totalWeight;
            $scope.updateClientOrder.orderSummaryDTO.totalGoodsWorth = totalWorth;
        });
        $scope.close = function () {
            $scope.updateWindow.close();
            $rootScope.reloadGrid();
        }
    }
})();